package com.wr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wr.alipay.config.AlipayConfig;
import com.wr.alipay.util.AlipayNotify;
import com.wr.alipay.util.AlipaySubmit;
import com.wr.model.EmailCodeEntity;
import com.wr.service.EmailService;
import com.wr.utils.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.wr")
public class TestRestfulController {

    private static Logger log = LoggerFactory.getLogger(TestRestfulController.class);

    private final EmailService emailService;

    @Autowired
    public TestRestfulController(EmailService emailService) {
        this.emailService = emailService;
    }

    @RequestMapping(value = "/test1/{email}",method = RequestMethod.POST)
    public ModelAndView testRestful1(@PathVariable String email){
        ModelAndView modelAndView = new ModelAndView();
        EmailCodeEntity emailCodeEntity = emailService.selectByEmail(email);
        modelAndView.addObject("code",emailCodeEntity.getCode());
        modelAndView.setViewName("hello");
        return modelAndView;
    }

    @RequestMapping(value = "/test2/{name}/{mobile}",method = RequestMethod.POST)
    public Map<String,Object> testRestful2(@PathVariable String mobile, @PathVariable String name){
        log.info(mobile);
        log.info(name);
        Map<String,Object> map = new HashMap<>();
        map.put("mobile",mobile);
        map.put("name",name);
        return map;
    }


    @RequestMapping(value = "/email", method = RequestMethod.POST)
    public Map<String,Object> insetEmailCode(EmailCodeEntity email){
        Map<String,Object> map = new HashMap<>();
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        email.setAddtime(sm.format(new Date()));
        emailService.insertEmailCode(email);
        System.out.println(email.toString());
        map.put("resultCode","201");
        return map;
    }

    @RequestMapping(value = "/email", method = RequestMethod.DELETE)
    public Map<String,Object> deleteEmailCode(EmailCodeEntity email){
        Map<String,Object> map = new HashMap<>();
        //emailService.deleteEmailCode(email.getId());
        System.out.println(email.getId());
        map.put("resultCode","200");
        return map;
    }

    @RequestMapping(value = "/email", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> updateEmailCode(EmailCodeEntity email){
        Map<String,Object> map = new HashMap<>();
        try {
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            email.setAddtime(sm.format(new Date()));
            System.out.println(email.toString());
            emailService.updateEmailCode(email);
            map.put("resultCode","200");
            //System.out.println(1/0);
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return map;
    }

    @RequestMapping(value = "/email", method = RequestMethod.GET)
    public Map<String,Object> selectEmailCode(EmailCodeEntity email){
        Map<String,Object> map = new HashMap<>();
        EmailCodeEntity emailCodeEntity = emailService.selectByEmail(email.getReceiveEmail());
        System.out.println(emailCodeEntity.toString());
        map.put("resultCode","200");
        return map;
    }

    @RequestMapping(value = "/toSelect2Page", method = RequestMethod.GET)
    public ModelAndView toSelect2Page(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("select2");
        return modelAndView;
    }

    @RequestMapping(value = "/loadingRemoteData", method = RequestMethod.POST)
    @ResponseBody
    public JSONArray loadingRemoteData(){
        StringBuilder json_friendsGroups = new StringBuilder();
        json_friendsGroups.append("[");
        for (int i=0;i<8;i++) {
            if(i == 7){
                json_friendsGroups.append("{id:").append(i).append(",text:\'").append(getRandomCharAndNum()).append("\'}");
            }else {
                json_friendsGroups.append("{id:").append(i).append(",text:\'").append(getRandomCharAndNum()).append("\'},");
            }
        }
        json_friendsGroups.append("]");
        return JSON.parseArray(json_friendsGroups.toString());
    }

    @RequestMapping(value = "/toElementPage", method = RequestMethod.GET)
    public ModelAndView toElementPage(PageInfo pageInfo){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("element");
        modelAndView.addObject("name","赵钱孙");
        modelAndView.addObject("region","shanghai");
        modelAndView.addObject("delivery","true");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[").append("\'地推活动\'").append(",").append("\'线下主题活动\'").append("]");

        List<EmailCodeEntity> list = emailService.selectCodeList(pageInfo);
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(list);
        modelAndView.addObject("list",jsonArray.toString());
        modelAndView.addObject("count",jsonArray.size());
        modelAndView.addObject("type",stringBuilder);
        modelAndView.addObject("resource","线下场地免费");
        modelAndView.addObject("desc","Form 组件提供了表单验证的功能，只需要通过 rule 属性传入约定的验证规则，并 Form-Item 的 prop 属相设置为需校验的字段名即可。");
        return modelAndView;
    }

    @RequestMapping(value = "/tablePage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> tablePage(PageInfo pageInfo){
        Map<String,Object> map = new HashMap<>();
        List<EmailCodeEntity> list = emailService.selectCodeList(pageInfo);
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(list);
        map.put("list",jsonArray);
        return map;
    }

    @RequestMapping(value = "/insertEmailCode", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> insertEmailCode(EmailCodeEntity emailCodeEntity,PageInfo pageInfo){
        Map<String,Object> map = new HashMap<>();
        emailService.insertEmailCode(emailCodeEntity);
        List<EmailCodeEntity> list = emailService.selectCodeList(pageInfo);
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(list);
        map.put("list",jsonArray);
        map.put("totalPage",pageInfo.getTotal());
        return map;
    }


    @RequestMapping(value = "/submitForm", method = RequestMethod.POST)
    public ModelAndView submitForm(String parameter,Long datetime) throws ParseException{
        ModelAndView modelAndView = new ModelAndView();
        JSONObject jsonObject = JSON.parseObject(parameter);
        Date date = new Date(datetime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonObject.put("date",sdf.format(date));
        System.out.println(jsonObject.toString());
        modelAndView.setViewName("redirect:toElementPage");
        return modelAndView;
    }

    private static String getRandomCharAndNum() {
        String str = "";
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            boolean b = random.nextBoolean();
            if (b) { // 字符串
                // int choice = random.nextBoolean() ? 65 : 97; 取得65大写字母还是97小写字母
                str += (char) (65 + random.nextInt(26));// 取得大写字母
            } else { // 数字
                str += String.valueOf(random.nextInt(10));
            }
        }
        return str;
    }


    /*@RequestMapping(value = "/alipay", method = RequestMethod.GET)
    public void testAliPay(HttpServletResponse response){
        Map<String,String> paramMap = new HashMap<>();
        SimpleDateFormat sm = new SimpleDateFormat("yyyyMMdd");
        paramMap.put("service", AlipayConfig.service);
        paramMap.put("partner",AlipayConfig.partner);
        paramMap.put("_input_charset",AlipayConfig.input_charset);
        paramMap.put("sign_type",AlipayConfig.sign_type);
        paramMap.put("notify_url",AlipayConfig.notify_url);
        //
        paramMap.put("account_name","吴睿");
        paramMap.put("detail_data","1003202^15723185442^罗丹^0.01^test");
        paramMap.put("batch_no","20170117002");
        paramMap.put("batch_num","1");
        paramMap.put("batch_fee","0.01");
        paramMap.put("email","15140230115");
        paramMap.put("pay_date",sm.format(new Date()));
        paramMap.put("buyer_account_name","15140230115");
        paramMap.put("extend_param","");
        String result = AlipaySubmit.buildRequest(paramMap,"get","确认");
        System.out.println(result);
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("text/html; charset=utf-8");
            response.getWriter().write(result);
            response.getWriter().close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/

    /*@RequestMapping("/payResult")
    public String payResult(HttpServletRequest request) throws IOException{
        String result = "pay_result";
        Map<String,Object> map = new HashMap<>();
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
        //金额
        String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        map.put("out_trade_no",out_trade_no);
        map.put("trade_no",trade_no);
        map.put("trade_status",trade_status);
        map.put("total_fee",total_fee);

        if(AlipayNotify.verify(params)) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            return result;
        }else{//验证失败
            return "404";
        }
    }*/
}
